/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.expert.web;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.CacheUtils;
import com.chlitina.store.common.utils.DateUtils;
import com.chlitina.store.common.utils.Encodes;
import com.chlitina.store.common.utils.excel.ExportExcel;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.Customer;
import com.chlitina.store.modules.base.entity.StoreCare;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.base.service.StoreCareService;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.cash.model.Member;
import com.chlitina.store.modules.cash.model.MemberShoppingCart;
import com.chlitina.store.modules.cash.model.SolutionStoreCareCart;
import com.chlitina.store.modules.cash.model.SolutionStoreProductCart;
import com.chlitina.store.modules.cash.service.MemberService;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.expert.entity.CustomerExam;
import com.chlitina.store.modules.expert.entity.CustomerSolution;
import com.chlitina.store.modules.expert.entity.CustomerSolutionAndCare;
import com.chlitina.store.modules.expert.entity.CustomerSolutionAndProduct;
import com.chlitina.store.modules.expert.entity.CustomerSolutionExport;
import com.chlitina.store.modules.expert.entity.CustomerSolutionMix;
import com.chlitina.store.modules.expert.entity.SolutionFace;
import com.chlitina.store.modules.expert.entity.SolutionFaceProductMix;
import com.chlitina.store.modules.expert.service.CustomerExamService;
import com.chlitina.store.modules.expert.service.CustomerSolutionMixService;
import com.chlitina.store.modules.expert.service.CustomerSolutionService;
import com.chlitina.store.modules.expert.service.SolutionFaceProductMixService;
import com.chlitina.store.modules.expert.service.SolutionFaceService;
import com.chlitina.store.modules.expert.utils.ExpertUtils;
import com.chlitina.store.modules.sms.quartz.CustomerTipQueueGenerate;
import com.chlitina.store.modules.sms.utils.SmsUtils;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;

/**
 * 客户采纳方案Controller
 * 
 * @author lvbo
 * @version 2013-06-20
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/expert/customerSolution")
public class CustomerSolutionController extends BaseController {

	@Autowired
	private CustomerSolutionService customerSolutionService;
	@Autowired
	private SolutionFaceService solutionFaceService;
	@Autowired
	private StoreProductService storeProductService;
	@Autowired
	private StoreCareService storeCareService;
	@Autowired
	private CustomerExamService customerExamService;
	@Autowired
	private CustomerTipQueueGenerate customerTipQueueGenerate;
	@Autowired
	private SolutionFaceProductMixService solutionFaceProductMixService;
	@Autowired
	private CustomerSolutionMixService customerSolutionMixService;
	@Autowired
	private MemberService memberService;

	@ModelAttribute
	public CustomerSolution get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return customerSolutionService.get(id);
		} else {
			return new CustomerSolution();
		}
	}

	private String getSelectPage(Page page, Long customerExamId) {
		Long customerSolution_id = (Long) CacheUtils.get("customerSolution_id");
		String currentId = "";
		if (customerSolution_id != null) {
			int index = customerSolutionService.getIndexById(
					customerSolution_id, customerExamId);
			ExpertUtils.setPageNoByCurrentId(page, index);
			currentId = String.valueOf(customerSolution_id);
			CacheUtils.remove("customerSolution_id");
		}
		return currentId;
	}

	@RequestMapping(value = { "list", "" })
	public String list(CustomerSolution customerSolution,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String ceId = request.getParameter("customerExamId");
		Long customerExamId = Long.parseLong(ceId);
		if (customerExamId != null) {
			Page<CustomerSolution> page = new Page<CustomerSolution>(request,
					response);
			String currentId = getSelectPage(page, customerExamId);
			Page<CustomerSolution> current_page = customerSolutionService.find(
					page, customerExamId);
			model.addAttribute("currentId", currentId);
			model.addAttribute("customerExamId", ceId);
			model.addAttribute("page", current_page);
		}
		return "modules/expert/customerSolutionList";
	}

	@RequestMapping(value = "manager")
	public String manager(long customerExamId, CustomerSolution customerSolution,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		CustomerExam customerExam = customerExamService.get(customerExamId);
		List<CustomerSolution> list = customerSolutionService.findByCustomerExam(customerExamId);
		model.addAttribute("list", list);
		model.addAttribute("customerExamId", customerExamId);
		model.addAttribute("customerName", customerExam.getEmployee().getName());
		return "modules/expert/customerSolutionManager";
	}

	@RequestMapping(value = "managerList")
	public String managerList(CustomerSolution customerSolution,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String status = request.getParameter("status");
		Store store = StoreUtils.getStore();
		Integer statusInt = null;
		if (status != null && !status.equals("-2")) {
			statusInt = Integer.valueOf(status);
		}
		String customerName = request.getParameter("customerName");
		Page<CustomerSolution> page = customerSolutionService.find(
				new Page<CustomerSolution>(request, response), customerName,
				statusInt);
		model.addAttribute("storeName", store.getName());
		model.addAttribute("status", status);
		model.addAttribute("customerName", customerName);
		model.addAttribute("page", page);
		return "modules/expert/customerSolutionManager";
	}

	@RequestMapping(value = "form")
	public String form(CustomerSolution customerSolution, Model model) {
		model.addAttribute("customerSolution", customerSolution);
		return "modules/expert/customerSolutionForm";
	}

	@ResponseBody
	@RequestMapping(value = "status")
	public String changeStatus(Integer newStatus,
			CustomerSolution customerSolution, ModelMap modelMap,
			RedirectAttributes redirectAttributes) {
		customerSolution.setStatus(newStatus);
		Calendar cal = Calendar.getInstance();
		customerSolution.setReal_end_date(cal.getTime());
		customerSolutionService.save(customerSolution);
		return "true";
	}

	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, HttpServletResponse response,String jsonData, String exam_id, Model model,
			RedirectAttributes redirectAttributes) {
		JSONObject allData = (JSONObject) JSONSerializer.toJSON(Encodes
				.unescapeHtml(jsonData));
		CustomerExam customerExam = customerExamService.get(Long
				.valueOf(exam_id));
		Employee employee = customerExam.getEmployee();
		Customer customer = customerExam.getCustomer();
		Member member = StoreUtils.getMember();
		if (member == null) {
			member = new Member();
			member.setCustomer(customer);
			request.getSession().setAttribute("member", member);
		}
		List<SolutionStoreProductCart>  solutionStoreProductCarts=new ArrayList<SolutionStoreProductCart>();
		List<SolutionStoreCareCart>  solutionStoreCareCarts=new ArrayList<SolutionStoreCareCart>();
		memberService.loadingMemberInfo(member);
		MemberShoppingCart shop = member.getShoppingCart();
		shop.setCustomerExam(customerExam);
		JSONArray solutionArray = allData.getJSONArray("solutionList");
		for (int i = 0; i < solutionArray.size(); i++) {
			int maxDays = 0;
			JSONObject solutionObject = (JSONObject) solutionArray.get(i);
			CustomerSolution customerSolution = new CustomerSolution();
			String solution_id = solutionObject.getString("solutionId");
			String checked = solutionObject.getString("checked");
			long solutionId = Long.valueOf(solution_id);
			SolutionFace solutionFace = solutionFaceService.get(solutionId);
			customerSolution.setStore(customerExam.getStore());
			customerSolution.setEmployee(customerExam.getEmployee());
			customerSolution.setCustomer(customer);
			customerSolution.setCustomerExam(customerExam);
			customerSolution.setSolutionFace(solutionFace);
			customerSolution.setStart_date(new Date());
			if (Boolean.valueOf(checked)) {
				customerSolution.setStatus(CustomerSolution.PROCEED_STATUS);
			} else {
				customerSolution.setStatus(CustomerSolution.UNADOPTED_STATUS);
				continue;
			}
			JSONArray mixList = solutionObject.getJSONArray("mixList");
			List<Long> mixListArray = ExpertUtils.toLongList(mixList);
			JSONArray productListArray = solutionObject
					.getJSONArray("productList");
			JSONArray foodListArray = solutionObject
					.getJSONArray("foodList");
			productListArray.addAll(foodListArray);
			for (int j = 0; j < productListArray.size(); j++) {
				JSONObject productObject = (JSONObject) productListArray.get(j);
				long id = productObject.getLong("productId");
				int productAmount = productObject.getInt("productAmount");
				int productDuration = productObject.getInt("productDuration");
				int productVolume = productObject.optInt("productVolume", 0);
				StoreProduct product = storeProductService.getByProduct(id);
				CustomerSolutionAndProduct csap = new CustomerSolutionAndProduct();
				csap.setStoreProduct(product);
				csap.setCustomerSolution(customerSolution);
				csap.setAmount(productAmount);
				int days = ExpertUtils.getMixProductDuration(solutionFace, id,
						productAmount, productVolume, mixListArray);
				if (days != -1) {
					productDuration = days;
				} else {
					productDuration = productDuration * productAmount;
				}
				if (productDuration > maxDays) {
					maxDays = productDuration;
				}
				int tipDays = SmsUtils.PRODUCT_TIP_DAYS;
				if (productDuration <= SmsUtils.PRODUCT_TIP_DAYS) {
					tipDays = productDuration - 1;
				}
				csap.setNotifyDate(ExpertUtils.getNotifyDate(productDuration,
						tipDays));
				customerSolution.getProductList().add(csap);
				// 购物车
				SolutionStoreProductCart storeProductCart= new SolutionStoreProductCart();
				storeProductCart.setStoreProduct(product);
				storeProductCart.setEmployee(employee);
				storeProductCart.setCount(productAmount);
				solutionStoreProductCarts.add(storeProductCart);
				shop.addSolutionStoreProduct(storeProductCart);
			}
			JSONArray careListArray = solutionObject.getJSONArray("careList");
			for (int j = 0; j < careListArray.size(); j++) {
				JSONObject careObject = (JSONObject) careListArray.get(j);
				String id = careObject.getString("careId");
				int careTimes = careObject.getInt("careTimes");
				int careDuration = careObject.getInt("careDuration");
				if (careDuration > maxDays) {
					maxDays = careDuration;
				}
				/**
				 * TODO:here may goes wrong.
				 */
				StoreCare storeCare = storeCareService.getByCare(Long
						.valueOf(id));
				System.out.println(storeCare.getId());
				CustomerSolutionAndCare csac = new CustomerSolutionAndCare();
				csac.setStoreCare(storeCare);
				csac.setCustomerSolution(customerSolution);
				csac.setRemain_times(careTimes);
				csac.setNotifyDate(ExpertUtils.getNotifyDate(careDuration,
						SmsUtils.CARE_TIP_DAYS));
				customerSolution.getCareList().add(csac);
				// 购物车
				SolutionStoreCareCart storeCareCart= new SolutionStoreCareCart();
				storeCareCart.setEmployee(employee);
				storeCareCart.setStoreCare(storeCare);
				storeCareCart.setCount(1);
				storeCareCart.setCareCount(careTimes);
				solutionStoreCareCarts.add(storeCareCart);
				shop.addSolutionStoreCare(storeCareCart);
			}
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DAY_OF_MONTH, maxDays);
			customerSolution.setPlan_end_date(cal.getTime());
			customerSolution.setReal_end_date(null);
			customerSolutionService.save(customerSolution);
			for (SolutionStoreProductCart cart : solutionStoreProductCarts) {
				cart.setSolutionID(customerSolution.getId());
			}
			//after ID updated, clear it.
			solutionStoreProductCarts.clear();
			for (SolutionStoreCareCart cart : solutionStoreCareCarts) {
				cart.setSolutionID(customerSolution.getId());
			}
			//after ID updated, clear it.
			solutionStoreCareCarts.clear();
			customerExam.getCustomerSolutionList().add(customerSolution);
			for (int j = 0; j < mixListArray.size(); j++) {
				CustomerSolutionMix mix = new CustomerSolutionMix();
				mix.setCustomerSolution(customerSolution);
				long mixId = mixListArray.get(j);
				SolutionFaceProductMix sm = solutionFaceProductMixService
						.get(mixId);
				mix.setSolutionFaceProductMix(sm);
				customerSolutionMixService.save(mix);
			}
		}
		customerExamService.save(customerExam);
		List<SolutionStoreProductCart> solutionProducts = member.getShoppingCart().getSolutionProducts();
		for (SolutionStoreProductCart solutionStoreProductCart : solutionProducts) {
			System.err.println("solution ID "+solutionStoreProductCart.getSolutionID());
		}
//		// 生产提醒短信
//		customerTipQueueGenerate.generate(customerExam
//				.getCustomerSolutionList());
		addMessage(redirectAttributes, "保存客户采纳方案成功");
		model.addAttribute("member", member);
		return "modules/cash/cashMemberDetail";
	}

	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		customerSolutionService.delete(id);
		addMessage(redirectAttributes, "删除客户采纳方案成功");
		return "redirect:" + Global.ADMIN_PATH
				+ "/modules/expert/customerSolution/?repage";
	}

	@RequestMapping(value = "export")
	public String exportFile(String status, String customerName,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		Store store = StoreUtils.getStore();
		Integer statusInt = null;
		if (status != null && !status.equals("-2")) {
			statusInt = Integer.valueOf(status);
		}
		String fileName = "";
		String errorMsg = "";
		ExportExcel writeFile = null;
		try {
			List<CustomerSolutionExport> customerSolutions = customerSolutionService
					.export(store, customerName, statusInt);
			if (customerSolutions == null || customerSolutions.size() == 0) {
				errorMsg = "不存在导出数据";
			} else {
				fileName = "solution" + DateUtils.getDate("yyyyMMddHHmmss")
						+ ".xls";
				writeFile = new ExportExcel("方案数据",
						CustomerSolutionExport.class, 1)
						.setDataList(customerSolutions);
				writeFile.write(response, fileName);
				return null;
			}
		} catch (Exception e) {
			errorMsg = "导出方案数据失败！";
			addMessage(redirectAttributes, errorMsg);
		} finally {
			if (writeFile != null) {
				writeFile.dispose();
			}
		}
		System.out.println(fileName);
		return "modules/expert/customerSolutionForm";
	}
}
